using System;
using System.IO;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Threading;
using EasoScreen.Plugins;

namespace EasoScreen;
public partial class MainWindow : Window
{
    XmlConfig xmlConfig = new XmlConfig();
    public MainWindow()
    {
        
        var serializer = new System.Xml.Serialization.XmlSerializer(typeof(XmlConfig));
        using var fileStream = new FileStream("Config.xml", FileMode.Open);
        xmlConfig = (XmlConfig)serializer.Deserialize(fileStream);
        InitializeComponent();
        DispatcherTimer timer = new DispatcherTimer();
        timer.Tick += Timer_Tick;
        timer.IsEnabled = true;
        IPAddress.Text = Core.Connection.GetIPAddress();
        PortNumber.Text = xmlConfig.PortNumber.ToString();
        QR.Source = QRCode.Generate($"{IPAddress.Text}:{PortNumber.Text}");
        ContentFrame.Children.Add(new AboutPage());

        foreach (var item in Nav.Items)
        {
            if (item is ListBoxItem listBoxItem && listBoxItem.Name == "About")
            {
                Nav.SelectedItem = listBoxItem;
                break;
            }
        }



    }

    private void Timer_Tick(object? sender, EventArgs e)
    {
        Hour.Text = DateTime.Now.ToString("HH");
        Minute.Text = DateTime.Now.ToString("mm");
        Date.Text = DateTime.Now.ToString("MM/dd");
        DayOfWeek.Text = DateTime.Now.DayOfWeek.ToString();
    }

    private void Config_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        ConfigButton.Flyout.ShowAt(ConfigButton);
    }

    private void ListBox_SelectionChanged(object? sender, SelectionChangedEventArgs e)
    {
        if (ContentFrame != null)
        {
            ContentFrame.Children.Clear();
            if (Nav.SelectedItem is ListBoxItem selectedItem)
            {
                switch (selectedItem.Name)
                {
                    case "About":
                        ContentFrame.Children.Add(new AboutPage());
                        break;
                    case "Scheduler":
                        ContentFrame.Children.Add(new Scheduler());
                        break;
                    default:
                        ContentFrame.Children.Add(new AboutPage());
                        break;
                }
            }
        }
    }

    private void PowerButton_Click(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
    {
        Close();
    }

    private async void Window_Initialized(object? sender, EventArgs e)
    { 
        Task task = new Task(() => Server.Program.StartServer(xmlConfig.PortNumber));
        task.Start();
        await task;

       
    }
}